//
//  HWDUpALIPhoto.m
//  Cxzc
//
//  Created by 张露杰 on 17/8/21.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "HWDUpALIPhoto.h"
#import <AliyunOSSiOS/OSSService.h>

//阿里云配置
NSString *const HWDALiOSSEndPoint = @"http://oss-cn-beijing.aliyuncs.com";
NSString *const HWDALiOSSAccessKeyId = @"LTAIfYlBAxMOUxn7";
NSString *const HWDALiAccessKeySecret = @"pmAInwBTaySznzgdFn2EYqYW1WQTAZ";
NSString *const HWDALiOSSBucketName = @"ccsd";

typedef void(^HWDUpALIPhotoSuccessBlock)(NSArray *);
typedef void(^HWDUpALIPhotoFailBlock)(void);
@interface HWDUpALIPhoto()

@property (nonatomic, copy) HWDUpALIPhotoSuccessBlock HWDUpALIPhotoSuccessblock;
@property (nonatomic, copy) HWDUpALIPhotoFailBlock HWDUpALIPhotoFailblock;

@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, retain) NSMutableArray *imageNames;
@property (nonatomic, retain) NSArray *images;
@property (nonatomic) NSInteger num;
@property (nonatomic) NSInteger maxNum;

@end

@implementation HWDUpALIPhoto
{
    OSSClient *_client;
}

- (instancetype)initWithImages:(NSArray *)images success:(void(^)(NSArray *imageNames))success fail:(void(^)(void))fail
{
    self = [super init];
    if (self) {
        _HWDUpALIPhotoSuccessblock = success;
        _HWDUpALIPhotoFailblock = fail;
        _maxNum = images.count;
        self.num = 0;
        _images = images;
        [self initOSSClient];
        [self upImageWithImages:images];
    }
    return self;
}

-(void)upImageWithImages:(NSArray *)images
{
    _imageNames = [NSMutableArray array];
    for (UIImage *image in images) {
        if ([image isKindOfClass:[UIImage class]]) {
            NSString *imageName = [[NSUUID UUID].UUIDString stringByAppendingString:@".png"];
            [_imageNames addObject:imageName];
            [self uploadImageWithImage:image imageName:imageName];
        }else
        {
            [_imageNames addObject:image];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.num++;
            });
        }
    }
}

/**
 上传图片
 
 @param image 图片
 */
-(void)uploadImageWithImage:(UIImage *)image imageName:(NSString *)imageName
{
    if (image) {
        __weak typeof(self) weakSelf = self;
        NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
            OSSPutObjectRequest * put = [OSSPutObjectRequest new];
            put.bucketName = HWDALiOSSBucketName;
            put.objectKey = imageName;
            put.uploadingData =  UIImageJPEGRepresentation(image, 0.2);
            put.uploadProgress =  ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
                // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
                
            };
            OSSTask *putTask = [self->_client putObject:put];
            [putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
                if (!task.error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.num++;
                    });
                } else {
                    NSLog(@"upload object failed, error: %@" , task.error);
                    [weakSelf.queue cancelAllOperations];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (weakSelf.HWDUpALIPhotoFailblock) {
                            weakSelf.HWDUpALIPhotoFailblock();
                        }
                    });
                }
                return nil;
            }];
        }];
        [weakSelf.queue addOperation:blockOperation];
    }
}

- (NSOperationQueue *)queue
{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc]init];
        _queue.maxConcurrentOperationCount = _images.count;
    }
    return _queue;
}

- (void)setNum:(NSInteger)num
{
    _num = num;
    if (_num == _maxNum) {
        if (_HWDUpALIPhotoSuccessblock) {
            for (int i = 0; i < _imageNames.count; i++) {
                if([_imageNames[i] rangeOfString:@"aliyuncs.com"].location == NSNotFound)
                {
                    [_imageNames replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%@%@",imageUrl,_imageNames[i]]];
                }
            }
            _HWDUpALIPhotoSuccessblock(_imageNames);
        }
    }
}

#pragma mark -- AliOSSClient
- (void)initOSSClient {
    //设置阿里OSSClient
    NSString *endpoint = HWDALiOSSEndPoint;
    
    // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的`访问控制`章节
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:HWDALiOSSAccessKeyId secretKey:HWDALiAccessKeySecret];
    _client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
}

@end
